import { RefObject, cloneElement, useCallback, useEffect, useRef, useState } from "react";


export default function useTimeout(fn: () => void, delay?: number){
    const fnRef = useRef<Function>(fn)
    // useRef 保存回调函数，每次调用都会更新这个函数，避免闭包陷阱（函数里引用之前的 state）, setTimeout 执行从 fnRef.current 取的最新的函数
    fnRef.current = fn
    const timerRef = useRef<number>()
    const clear = useCallback(
      () => {
        if (timerRef.current) {
          clearTimeout(timerRef.current)
        }
      },
      [],
    )

    useEffect(() => {
      timerRef.current = setTimeout(fnRef.current, delay);
      return clear
    }, [delay]);

    return clear
}